'use strict'
const SUN = require('../base/sun')
const nodeMgr = require('../code/nodeMgr')
const sessionMgr = require('../code/sessionMgr')
const sceneMgr = require('../code/sceneMgr')
const userDao = require('../dao/userDao')
const route = require('../module/route')


route.setNotLogin('getErrMap', function (session, msg, next) {
    next(0, route.errMap)
}, {
    101: '数据库错误',
    102: '系统错误',
    103: '参数错误'
})

//用户注册
route.setNotLogin('userRegister', function (session, msg, next) {
    let password = msg.password
    let username = msg.username
    let ret = SUN.verification(msg, [
        ['username', 'string', /^([a-z]|[A-Z]|[0-9]){1,16}$/],
        ['password', 'string', /^([a-z]|[A-Z]|[0-9]){1,16}$/]
    ])
    if (ret) {
        next(103, ret)
        return
    }

    //判断名字是否已经存在
    userDao.getUserByName(username, function (err, res) {
        if (err) {
            next(101)
            return
        }
        if (res) {
            next(2)
            return
        }
        userDao.newAndSave(username, password, function (err, ret) {
            if (err) {
                next(101)
                return
            }
            next(0)
        })
    })
}, {
    2: '名字已经存在',
})


//用户登陆
route.setNotLogin('userLogin', function (session, msg, next) {
    let password = msg.password
    let username = msg.username
    let ret = SUN.verification(msg, [
        ['username', 'string', /^([a-z]|[A-Z]|[0-9]){1,16}$/],
        ['password', 'string', /^([a-z]|[A-Z]|[0-9]){1,16}$/]
    ])
    if (ret) {
        next(103, ret)
        return
    }
    userDao.getUserByQuery({
        username: username,
        password: password
    }, function (err, ret) {
        if (err) {
            next(101)
            return
        }
        if (!ret) {
            next(2)
            return
        }

        let node = nodeMgr.getRandomNode()
        session.nodeId = node.id
        session.uId = ret._id
        next(0)

    })
}, {
    2: '用户名不存在或密码错误'
})

//心跳
route.set('heartbeat', function (session, msg, next) {
    session.heartbeat = 0
    next(0)
})

//获取名称列表
route.setNotLogin('getPropName', function (session, msg, next) {
    next(0, SUN.propName)
})

//获取配置
route.setNotLogin('getTotalConfig', function (session, msg, next) {
    next(0, SUN.totalConfig)
})